# -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 16:55:15 2017

@author: xuanlei
"""

from tensorflow.examples.tutorials.mnist import input_data as inpd
import tensorflow as tf
import numpy as np
# 在这里做数据加载，MNIST的数据，以one_hot的方式加载数据，目录可以是已经下载完成的目录，这里已经下载完成‘MNIST_data’
mnist = inpd.read_data_sets("MNIST_data/", one_hot=True)


# MNIST的数据是一个28*28的图像，这里RNN测试，把他看成一行行的序列（28维度（28长的sequence）*28行）


# 定义RNN学习时使用的参数
learning_rate = 0.01       #学习率
training_iters = 100000    #迭代次数
batch_size = 128           #每次迭代输入的数据量
display_step = 10          #显示的步数间隔，后面会知道其作用


# 神经网络的参数

n_input = 28               # 输入层的n
n_steps = 28               # 28长度
n_hidden = 128             # 隐含层的特征数
n_classes = 10             # 输出的数量，因为是分类问题，0~9个数字，这里一共有10个

# 构建tensorflow的输入X的placeholder
x = tf.placeholder("float", [None, n_steps, n_input])
# tensorflow里的LSTM需要两倍于n_hidden的长度的状态，一个state和一个cell
# 输出Y
y = tf.placeholder("float", [None, n_classes])

# 每一层的权值和偏置
weights = {
    'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])),  # Hidden layer weights
    'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
    'hidden': tf.Variable(tf.ones([n_hidden])),
    'out': tf.Variable(tf.ones([n_classes]))
}


# 构建RNN

def RNN(_X, _weights, _biases):
    '''
          这里构建了最简单的单层RNN，输入为训练数据、权重W、偏执B
     _X, _weights, _biases
    
    '''
    #LSTM的基本结构cell
    lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
    #cell的状态
    cells_init_state = lstm_cell.zero_state(batch_size,dtype=tf.float32)
    #cell的输出
    outputs, states = tf.nn.dynamic_rnn(lstm_cell, _X, initial_state=cells_init_state)
#    print(outputs.shape)
    # 输出层
    return tf.matmul(tf.transpose(outputs,[1,0,2])[-1], _weights['out']) + _biases['out']


pred = RNN(x, weights, biases)

# 定义损失和优化方法，softmax交叉熵，优化方法为Adam
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))  # Softmax loss
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)  # Adam Optimizer

# 进行模型的评估，argmax是取出取值最大的那一个的标签作为输出
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# 初始化
init = tf.initialize_all_variables()

# 开始运行

with tf.Session() as sess:
    tf.reset_default_graph()
    sess.run(init)
    step = 1
    # 持续迭代
    while step * batch_size < training_iters:
        # 随机抽出这一次迭代训练时用的数据
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        # 对数据进行处理，使得其符合输入
        batch_xs = batch_xs.reshape((batch_size, n_steps, n_input))
        # 迭代
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
        # 在特定的迭代回合进行数据的输出
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})
            print("Iter " + str(step * batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + \
                  ", Training Accuracy= " + "{:.5f}".format(acc))
        step += 1
    print("Optimization Finished!")
    # 载入测试集进行测试
#     test_len = 128
#     test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
#     test_label = mnist.test.labels[:test_len]
#     print("Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label}))